/*
 * inotify-sync - a simple file synchronizer and file system watcher
 * Copyright (C) 2010-2011, inotify-sync developers and inotify-sync contributors
 * Copyright (C) 2010-2011, Cohesion Network Security Studio
 *
 * inotify-sync is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * inotify-sync is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with inotify-sync; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * FILE:			ConfigXml.cpp
 * USAGE:			---
 * DESCRIPTION:		---
 * OPTIONS:			---
 * REQUIREMENTS:	---
 * BUGS:			---
 * NOTES:			---
 * AUTHOR:			LI Yiwei (mail:leeyiw@gmail.com)
 * COMPANY:			---
 * VERSION:			1.0
 * CREATED:			Thu Oct 20 16:54:11 CST 2011
 * REVISION:		---
 */

#include "ConfigXml.h"

ConfigXml::ConfigXml()
try
:
p_doc(0),
p_root_node(0),
p_cur_node(0)
{
/*检测是否存在conf文件，如果不存在或无读或写权限，则直接报错退出*/
	int ret=0;
	if(0==(ret=access(CONF_PATH,F_OK)))
	{
		if(0==(ret=access(CONF_PATH,R_OK|W_OK)))
		{
			xmlKeepBlanksDefault(0);
			p_doc=xmlReadFile(CONF_PATH,
					"UTF-8",
					XML_PARSE_RECOVER);	
			p_root_node=xmlDocGetRootElement(p_doc);
		}
		else
			throw Error(errno,E_CONFPERMDENY);
	}
	else
		throw Error(errno,E_CONFNOTEXIST);
}
catch(Error& error)
{
	error.print_error();
	exit(error.get_error_id());
}

ConfigXml::~ConfigXml()
{
	xmlSaveFormatFileEnc(CONF_PATH,
				p_doc,"UTF-8",1);
	xmlFreeDoc(p_doc);
	xmlCleanupParser();
	xmlMemoryDump();
}

bool
ConfigXml::get_config(Config& config)
{
	p_cur_node=p_root_node->xmlChildrenNode;
	while(0!=p_cur_node)
	{
		const xmlChar *p_conf_name=p_cur_node->name;
		if(!xmlStrcmp(p_conf_name,BAD_CAST"profile_path"))
		{
			xmlChar *content=xmlNodeGetContent(p_cur_node);
			config.set_profile_path((const char*)content);
			return true;
		}
		else
			p_cur_node=p_cur_node->next;
	}
	return false;
}
